package com.thoughtworks.studio.tools.cardkit;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.thoughtworks.studio.tools.cardkit.generator.CardImageGenerator;
import com.thoughtworks.studio.tools.cardkit.parser.CardkitParser;
import com.thoughtworks.studio.tools.cardkit.parser.ExcelParser;
import com.thoughtworks.studio.tools.graphics.ImageGenerator;

public class CardFactory {
	private CardImageGenerator imageCreator;
	private CardkitParser parser;
	private Map<String,Card> cards = new HashMap<String,Card>();
	public CardFactory(CardImageGenerator imagecreator, CardkitParser parser) {
		this.imageCreator = imagecreator;
		this.parser = parser;
	}

	public CardImageGenerator getImageCreator() {
		return imageCreator;
	}

	public void createCardImages(){
		for (Iterator<Card> iterator = cards.values().iterator(); iterator.hasNext();) {
			Card card = iterator.next();
			this.imageCreator.generate(card);
		}
	}
	public Map<String,Card> getCards(){
		return cards;
		
	}
	public void init() throws FileNotFoundException, IOException{
		List<List<Object>> data = parser.parse();
		List<Object> list = (List<Object>)data.get(0);
		List<Object> prop = list;
		String eachProp = null;
		Object eachValue = null;
		for(int i=1;i<data.size();i++){
			Card card= new Card();
			List<Object> rowdata= data.get(i);
			for(int j=0;j<prop.size()-1;j++){
				eachProp = (String)prop.get(j);
				eachValue = rowdata.get(j)==null?"":rowdata.get(j);
				card.setPorperty(eachProp,eachValue);
				String value= String.valueOf(eachValue);
				if(eachProp.equals("Number"))
					card.setNumber(value.substring(0, value.length()-2));
				if(eachProp.equals("Name"))
					card.setName(String.valueOf(eachValue));
			}
			cards.put(card.getNumber(),card);
		}
	}

	public void setImageCreator(CardImageGenerator imageCreator) {
		this.imageCreator = imageCreator;
	}
	public static void main(String[] args) throws Exception {
		File file = new File("c:\\book1.xls");
		CardFactory factory = new CardFactory(new CardImageGenerator(new ImageGenerator()), new CardkitParser(new ExcelParser(file)) );
		factory.init();
		factory.createCardImages();
	}
	
}